package net.steam.easyjoboa.web.action;

import java.io.IOException;
import java.util.List;
import net.steam.easyjoboa.dao.MenuDao;
import net.steam.easyjoboa.entity.Employee;
import net.steam.easyjoboa.entity.Menu;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

public class MenuAction {

	private MenuDao menuDao;

	private String menuStr;
	private String atid;

	@Action(value="menu")
	public void showMenu() {
		StringBuffer str = new StringBuffer("");
		Employee employee= (Employee) ServletActionContext.getRequest().getSession().getAttribute("loginUser");
		List<Menu> menus = menuDao.findMenuByRole(employee.getUserId(), atid);
		for (Menu menu : menus) {
			str.append(",[" + menu.getMenuId() + "," + menu.getParentId()
					+ ",'" + menu.getMenuName() + "'");
			if (menu.getResurl() == null || menu.getResurl().equals("")) {
				str.append(",1");
			} else {
				str.append(",0");
			}
			str.append(",'" + menu.getResurl() + "']");
		}
		String outStr = "";
		if (str.length() > 0) {
			outStr = str.substring(1);
		}
		outStr = "[" + outStr + "]";
		System.out.println(outStr);
		try {
			ServletActionContext.getResponse().setContentType(
					"text/html;charset=utf-8");
			ServletActionContext.getResponse().getWriter().write(outStr);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Action(value="showTreeMenu",results={@Result(name="success",location="/menuTree.jsp")})
	public String showTreeMenu(){
		StringBuffer str = new StringBuffer("");
		Employee employee= (Employee) ServletActionContext.getRequest().getSession().getAttribute("loginUser");
		List<Menu> menus = menuDao.findMenuByRole2(employee.getUserId());
		str.append("<script type=\"text/javascript\">\n");
		str.append("d = new dTree('d');\n");
		str.append("d.add(0, -1, '系统菜单');\n");
		for (Menu menu : menus) {
			str.append("d.add("+menu.getMenuId()+"," + menu.getParentId()
					+ ",'" + menu.getMenuName()+"'");
			if (menu.getResurl() == null || menu.getResurl().equals("")) {
				str.append(",''");
			} else {
				str.append(",'"+menu.getResurl()+"','','mainFrame'");
			}
			str.append(");\n");
		}
		str.append("document.write(d);\n");
		str.append("</script>");
		menuStr = str.toString();
		//System.out.println(menuStr);
		return "success";
	}
	
	public void setMenuDao(MenuDao menuDao) {
		this.menuDao = menuDao;
	}

	public String getAtid() {
		return atid;
	}

	public void setAtid(String atid) {
		this.atid = atid;
	}

	public String getMenuStr() {
		return menuStr;
	}

	public void setMenuStr(String menuStr) {
		this.menuStr = menuStr;
	}

}
